package com.ruoyi.tiktok.service;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.tiktok.domain.Task;
import com.ruoyi.tiktok.domain.TaskVideoRelation;
import com.ruoyi.tiktok.mapper.TaskVideoRelationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.tiktok.mapper.taskMapper;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
public class TaskService {
    @Value("${tuike.taskAddress}")
    private   String baseTaskAddress;
    @Autowired
    private taskMapper taskMapper;
   @Autowired
   private TaskVideoRelationMapper taskVideoRelationMapper;

   public AjaxResult createTask(Task task) {
       String taskId = generateTimeId();
       task.setTaskId(taskId);
       task.setTaskCreateTime(Date.valueOf(LocalDate.now()));
       task.setTaskAddress(genTaskAddress(taskId));
       ArrayList<JSONObject> videos = task.getAddVideos();
       if(videos.size()==0){
          return AjaxResult.error("请绑定推广所需要的视频");
       } else {
           // select get video id...
           taskMapper.insertTask(task);
           for (int i = 0; i < videos.size(); i++) {
               Long fileId = Long.valueOf(videos.get(i).getString("fileId"));
               taskVideoRelationMapper.insertRelation(new TaskVideoRelation(taskId, fileId));
           }
           return  AjaxResult.success("创建成功");
       }
   }


   public List<?> selectTaskList(Task task){
       return taskMapper.selectTasksList(task);
   }
   private String generateTimeId(){
       SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
       String dateTime= simpleDateFormat.format(new java.util.Date());
       Random random = new Random();
       int endNo = random.nextInt(999);
       return  dateTime + String.format("%03d", endNo);
   }
   private String genTaskAddress(String taskId){
       return  baseTaskAddress +"?taskId="+ taskId;
   }

    public Task selectTasksByTaskId(String taskId) {
       return taskMapper.selectTasksByTaskId(taskId);
    }


    public int changeTaskStatus(Task task){
       String status = task.getTaskStatus();
        if ("1".equals(status) ||"0".equals(status)) {
            return  taskMapper.updateTasks(task);
        } else {
            return -1;
        }
    }

    public int updateTask(Task task){
       return  taskMapper.updateTask(task);
    }
}

